package cn.ly.design.action.clazz;

import java.util.ArrayList;
import java.util.List;

public class ObserverTest {

	public static void main(String[] args) {  
        Subject sub = new MySubject();  
        sub.add(new Observer1());  
        sub.add(new Observer2());  
        sub.operation();  
    }  
	
}


interface IObserver {  
    public void update();  
}  

class Observer1 implements IObserver {  
  
    @Override  
    public void update() {  
        System.out.println("observer1 has received!");  
    }  
}  

class Observer2 implements IObserver {  
  
    @Override  
    public void update() {  
        System.out.println("observer2 has received!");  
    }  
  
}  

interface Subject {  
      
    /*增加观察者*/  
    public void add(IObserver observer);  
      
    /*删除观察者*/  
    public void del(IObserver observer);  
      
    /*通知所有的观察者*/  
    public void notifyObserver();  
      
    /*自身的操作*/  
    public void operation();  
}  


abstract class AbstractSubject implements Subject {  //抽象类实现接口，可以不完全实现所有的方法，只实现一些公共的就可以
  
    private List<IObserver> list = new ArrayList<IObserver>();  
    @Override  
    public void add(IObserver observer) {  
        list.add(observer);  
    }  
  
    @Override  
    public void del(IObserver observer) {  
        list.remove(observer);  
    }   

    @Override
    public void notifyObserver(){
    	for(IObserver o : list){
    		o.update();
    	}
    }
}


class MySubject extends AbstractSubject {  //具体操作交给子类去处理
    @Override  
    public void operation() {  
        System.out.println("my subject update!");  
        notifyObserver();
    }

}  
